import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button, Icon, Form, Switch, Radio, Checkbox, Row, Col, Input, Collapse, Popconfirm } from 'antd';
import { messages } from 'share/common';
import SlideFrame from 'components/slide-frame';
import Priority from 'components/template/priority';
import 'styles/setting/notification-setting/message-remind.scss';
import configureStore from 'stores';
import config from 'config';
import Chooser from 'components/chooser';
import { LanguageInput } from 'components/index';
import NotificationContentService
  from 'containers/setting/notification-setting/notification-content/notification-content.service';
import moment from 'moment';
import { message } from 'antd/lib/index';
import errorMessage from 'share/errorMessage';

const Panel = Collapse.Panel;

const remindSelectorItem = {
  title: messages('basic-13.key1')/*请选择提醒规则*/,
  url: `${config.baseUrl}/api/remind/regulation/list?isEnabled=true`,
  searchForm: [
    {type: 'input', id: 'regulationCode', label: messages('basic-13.key2')/*提醒规则代码*/},
    {type: 'input', id: 'regulationName', label: messages('basic-13.key3')/*提醒规则名称*/}
  ],
  columns: [
    {title: messages('basic-13.key2')/*提醒规则代码*/, dataIndex: 'regulationCode'},
    {title: messages('basic-13.key4')/*规则名称*/, dataIndex: 'regulationName'},
  ],
  key: 'id'
};

const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 16, offset: 1},
};

@Form.create()
class MessageRemind extends Component {
  constructor (props) {
    super(props);
    const {tenant} = this.props;
    this.state = {
      remindList: [],
      remindData: {},
      priority: {
        levelCode: 'TENANT',
        llevelOrgName: tenant.tenantName,
        levelOrgId: tenant.id
      },
      isShowSlideFrame: false,
      isSpecifiedPersonSelected: false,
      remainCount: 300,
      loading: false,
      notificationMethod: {}

    };
    this.remindTitle = {
      'OCR': 'OCR服务续费提醒',
      'CHECK_INVOICE': '发票查验服务续费提醒'
    };
    this.remindInfo = {
      'OCR': (tenantName, remainCount) => `${tenantName} 购买的OCR服务，剩余可用数量为 ${remainCount} 张，系统将于剩余数量小于等于0时自动关闭服务。\n请管理员在汇联易平台-管理员首页-购买对应服务续费。`,
      'CHECK_INVOICE': (tenantName, remainCount) => `${tenantName} 购买的发票查验服务，剩余可用数量为 ${remainCount} 张，系统将于剩余数量小于等于0时自动关闭服务。\n请管理员在汇联易平台-管理员首页-购买对应服务续费。`
    };
  }

  componentDidMount () {
    console.log('messageRemind componentDidMount', this.props);
    this.getNotificationClientTypes();
    this.getList();
  }

  getNotificationClientTypes = () => {
    NotificationContentService.getNotificationRulesMethods()
      .then(res => {
        let list = {};
        res.data.forEach(item => {
          list[item.value] = item.messageKey;
        });
        this.setState({
          notificationMethod: list
        });
      });
  };

  getList = () => {
    NotificationContentService.getOcrOrInvioceRemindStrategy(this.props.type)
      .then(res => {
        console.log('getList', res);
        let {data} = res;
        if (data) {
          this.setState({
            remindList: data
          });
        }
      });
  };

  onSpecifiedPersonSelected = (e) => {
    this.setState({
      isSpecifiedPersonSelected: !this.state.isSpecifiedPersonSelected
    });
  };
  onRenewRemindTargetsChanged = (data) => {
    console.log('onRenewRemindTargetsChanged', data);
    this.setState({
      renewRemindTargets: data
    });
  };
  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      let {remindData}= this.state
      console.log('handleSave', values);
      let renewRemindTargets = [];
      if (this.state.isSpecifiedPersonSelected) {
        renewRemindTargets = values.renewRemindTargets.map(item => {
          return {
            userId: item.id
          };
        });
      }

      let postData = {
        serviceTypeCode: this.props.type,
        remainCount: this.state.remainCount,
        regulationId: values.remindRegulation[0] && values.remindRegulation[0].id,
        renewRemindTargets: renewRemindTargets
      };
      this.setState({
        loading: true
      });
      let proIns= null
      let msg= messages('common.save.success',{arg1: ""})/*{arg1} 保存成功*/
      if(remindData.id){
        postData.id= remindData.id
        proIns = NotificationContentService.putOcrOrInvioceRemindStrategy(postData)
        msg= messages('basic-13.key5')/*更新成功*/
      } else {
        proIns = NotificationContentService.postOcrOrInvioceRemindStrategy(postData)
      }

      proIns
        .then(res => {
          message.success(msg);
          this.setState({
            loading: false
          });
          console.log('postOcrOrInvioceRemindStrategy', res);
          this.onCancel();
          this.getList();
        })
        .catch(err => {
          this.setState({
            loading: false
          });
          errorMessage(err.response);
        });
    });
  };
  onCancel = () => {
    this.setState({
      isShowSlideFrame: false
    });
  };
  renderForm = () => {
    const {type} = this.props;
    const {getFieldDecorator} = this.props.form;
    const {priority, isShowSlideFrame, isSpecifiedPersonSelected, remindData, remainCount, loading} = this.state;
    console.log('renderForm', remindData);
    let title= messages('basic-13.key6')/*新建消息设置*/
    if(remindData.id){
      title= messages('basic-13.key7')/*编辑消息设置*/
    }
    let remindTitle= this.remindTitle[type];
    console.log('remindTitle', remindTitle);
    return (
      <SlideFrame
        title={title}
        show={isShowSlideFrame}
        onClose={this.onCancel}
      >
        <div className={'remind-form-wrapper'}>
          <Form className={'new-form'}>
            <Form.Item
              label={messages('common.column.status')/*状态*/}
              {...formItemLayout}
            >
              {getFieldDecorator('enabled', {
                rules: [{required: true}],
                valuePropName: 'checked',
                initialValue: remindData.hasOwnProperty('enabled') ? remindData.enabled : true
              })(
                <Switch>{messages('basic-13.key8')/*启用temp*/}</Switch>
              )}
            </Form.Item>
            <Form.Item
              label={messages('basic-13.key9')/*所属组织*/}
              {...formItemLayout}
            >
              {getFieldDecorator('priority', {
                rules: [{required: true}],
                initialValue: priority
              })(
                <Priority
                  formItemLayout={{...formItemLayout}}
                  showLabel={false}
                  top={'TENANT'}
                  disabled={true}
                  defaultValue={priority}
                  onlyTenant
                  required={true}
                />
              )}
            </Form.Item>
            <Form.Item
              label={messages('basic-13.key10')/*引用消息提醒规则*/}
              {...formItemLayout}
            >
              {getFieldDecorator('remindRegulation', {
                rules: [{
                  required: true,
                  message: messages('basic-13.key11')/*请选择引用的消息规则*/
                }],
                initialValue: remindData.hasOwnProperty('remindRegulation') ? remindData.remindRegulation : []
              })(
                <Chooser
                  single={true}
                  placeholder={messages('common.select')/*请选择*/}
                  labelKey='regulationName'
                  valueKey='id'
                  selectorItem={remindSelectorItem}
                />
              )}
            </Form.Item>
            <div className="sub-title">{messages('basic-13.key12')/*提醒对象*/}</div>
            <Form.Item
              label={messages('basic-13.key12')/*提醒对象*/}
              {...formItemLayout}
            >
              {getFieldDecorator('superAdmin', {
                rules: [{required: true}],
                initialValue: true
              })(
                <Checkbox defaultChecked={true} disabled={true}>{messages('basic-13.key13')/*全租户权限的超级管理员角色*/}</Checkbox>
              )}
            </Form.Item>
            <div className="wrapper">
              <Row span={24}>
                <Col span={16} offset={6}>
                  <Checkbox checked={isSpecifiedPersonSelected}
                            onChange={this.onSpecifiedPersonSelected}>{messages('basic-13.key14')/*指定人员*/}</Checkbox>
                </Col>
              </Row>
              <Row span={24} style={{marginTop: 5}}>
                <Col span={16} offset={6}>
                  <Form.Item>
                    {getFieldDecorator('renewRemindTargets', {
                      initialValue: remindData.hasOwnProperty('renewRemindTargets') ? remindData.renewRemindTargets : []
                    })(
                      <Chooser
                        type={'user'}
                        single={false}
                        valueKey={'id'}
                        labelKey={'fullName'}
                        placeholder={messages('common.select')/*请选择*/}
                      />
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </div>
            <div className="sub-title">{messages('basic-13.key15')/*消息内容*/}</div>
            <Form.Item
              label={messages('basic-13.key16')/*消息标题*/}
              {...formItemLayout}
            >
              {getFieldDecorator('remindTitle', {
                rules: [{required: true}],
                initialValue: remindTitle
              })(
                <LanguageInput
                  disabled={true}
                  buttonDisabled
                ></LanguageInput>
              )}
            </Form.Item>
            <Form.Item
              label={messages('basic-13.key17')/*消息正文*/}
              {...formItemLayout}
            >
              {getFieldDecorator('remindInfo', {
                rules: [{required: true}],
                initialValue: this.remindInfo[type](this.props.tenant.tenantName, this.state.remainCount)
              })(
                <LanguageInput
                  textArea={true}
                  disabled={true}
                  buttonDisabled
                  textAreaFormat={'hard'}/>
              )}
            </Form.Item>
            <div className="sub-title">{messages('basic-13.key18')/*消息触发*/}</div>
            <Form.Item
              label={messages('basic-13.key19')/*触发条件*/}
              {...formItemLayout}
            >
              {getFieldDecorator('remainCount', {
                rules: [{required: true}],
                initialValue: remainCount
              })(
                <div>
                  <span>{messages('basic-13.key20')/*剩余张数为*/}</span>
                  <Input className={'remind-number-input'} type={'number'} value={remainCount}
                         onInput={(e) => this.setState({remainCount: e.target.value})}/>
                  <span>{messages('basic-13.key21')/*张时发起提醒*/}</span>
                </div>
              )}
            </Form.Item>
          </Form>
          <div className="slide-footer">
            <Button type="primary" onClick={this.handleSave}
                    loading={loading}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </div>
      </SlideFrame>);
  };

  handleNew = () => {
    this.props.form.resetFields();
    this.setState({
      isShowSlideFrame: true,
      remainCount: 300,
      isSpecifiedPersonSelected: false,
      remindData: {}
    });
  };

  onEditRemind = (data) =>{
    this.props.form.resetFields();
    let {remindRegulation, renewRemindTargets=[]}= data
    this.setState({
      isShowSlideFrame: true,
      remainCount: data.remainCount,
      isSpecifiedPersonSelected: !!(data.renewRemindTargets && data.renewRemindTargets.length > 0),
      remindData: {
        id: data.id,
        renewRemindTargets: renewRemindTargets.map(person=>{
          return {
            id: person.userId,
            fullName: person.userName
          }
        }),
        remindRegulation:[{
          id: remindRegulation.id,
          regulationName: remindRegulation.regulationName
        }]
      }
    });
  }

  onDeleteRemind= (data)=>{
    NotificationContentService.deleteOcrOrInvioceRemindStrategy(data)
      .then(res=>{
        let {data}= res
        if(data){
          message.success(messages('common.delete.successful')/*删除成功*/);
          this.getList()
        }
      })
  }

  analyzeRule (remindRegulationDTO) {
    let weekDate = {
      MON: messages('basic-13.key22')/*每周一*/,
      TUE: messages('basic-13.key23')/*每周二*/,
      WED: messages('basic-13.key24')/*每周三*/,
      THU: messages('basic-13.key25')/*每周四*/,
      FRI: messages('basic-13.key26')/*每周五*/,
      SAT: messages('basic-13.key27')/*每周六*/,
      SUN: messages('basic-13.key28')/*每周日*/,
    };
    let remindDayArr = [];
    let remindClientsArr = [];
    remindRegulationDTO.remindDays.forEach(item => {
      remindDayArr.push(weekDate[item]);
    });
    remindRegulationDTO.remindClients.forEach(item => {
      remindClientsArr.push(this.state.notificationMethod[item] || item);
    });
    let remindTimes= remindRegulationDTO.remindTimes || []
    if(remindRegulationDTO.remindDateTime){
      remindTimes= remindTimes.concat(moment(remindRegulationDTO.remindDateTime).format('YYYY-MM-DD hh:mm:ss'))
    }
    return {
      remindClientsArr: remindClientsArr,
      remindTimes: remindTimes,
      remindDayArr: remindDayArr,
    };
  }

  renderPanelHeader = (remind) => {
    return (
      <div className="display-title-wrapper">
        <div className="display-title">{remind.title}</div>
        {!this.props.disabled &&
        <div className="display-btn-group">
          <div className="btn btn-edit" onClick={(e)=>(e.stopPropagation(),this.onEditRemind(remind))}>{messages('common.edit')/*编辑*/}</div>
          <Popconfirm onConfirm={() => {this.onDeleteRemind(remind)}}
                      onClick={e => e.stopPropagation()}
                      title={messages('basic-13.key29')/*你确定要删除这条数据吗?*/}>
            <div className="btn btn-delete">{messages('common.delete')/*删除*/}</div>
          </Popconfirm>
        </div>
        }
      </div>);
  };
  renderCloumn = (label, value) => {
    return <Row span={22}>
      <Col span={3}>{label}:</Col>
      <Col span={18}>{value}</Col>
    </Row>;
  };

  render () {
    const {remindList, priority} = this.state;
    return (
      <div className={'message-remind-wrapper'}>
        <div className="remind-content">
          <div className="remind-info">{messages('basic-13.key30')/*1.消息提醒可引用已配置的提醒规则*/}</div>
          {
            remindList && remindList.map(remind => {
              let {remindRegulation} = remind;
              const {remindClientsArr, remindTimes, remindDayArr} = this.analyzeRule(remindRegulation);
              return <Collapse key={remind.id} bordered={false}>
                <Panel header={this.renderPanelHeader(remind)}>
                  <div className="remind-display">
                    {this.renderCloumn(messages('common.column.status')/*状态*/, remind.enabled? messages('basic-13.key8')/*启用temp*/: messages('basic-13.key31')/*禁用temp*/)}
                    {this.renderCloumn(messages('basic-13.key32')/*组织层级*/, remind.tenantName)}
                    {this.renderCloumn(messages('basic-13.key12')/*提醒对象*/,
                      [`全租户权限的超级管理员角色`].concat(remind.renewRemindTargets.map(item => item.userName)).join('、'))}
                    {this.renderCloumn(messages('basic-13.key16')/*消息标题*/, remind.title)}
                    {this.renderCloumn(messages('basic-13.key17')/*消息正文*/, this.remindInfo[this.props.type](remind.tenantName, remind.remainCount))}
                    {this.renderCloumn(messages('basic-13.key19')/*触发条件*/, messages('basic-13.key33',{arg1: remind.remainCount})/*剩余张数为 {arg1} 张时发起提醒*/)}
                    {remindClientsArr.length > 0 && this.renderCloumn(messages('basic-13.key34')/*提醒方式*/, remindClientsArr.join('、'))}
                    {remindTimes.length > 0 && this.renderCloumn(messages('basic-13.key35')/*提醒时间*/, remindTimes.join('、'))}
                    {remindDayArr.length > 0 && this.renderCloumn(messages('basic-13.key36')/*重复提醒*/, remindDayArr.join('、'))}
                  </div>
                </Panel>
              </Collapse>;
            })
          }
          <div className="btn-add-wapper">
            <Button
              disabled={this.props.disabled}
              type="dashed"
              className="btn-add"
              onClick={this.handleNew}
            >
              <Icon type="plus"/>{messages('common.add')/*添加*/}{/*添加*/}
            </Button>
          </div>
        </div>
        {this.renderForm()}
      </div>
    );
  }
}

MessageRemind.propTypes = {
  name: React.PropTypes.string,
  type: React.PropTypes.string,
  disabled: React.PropTypes.boolean,
};

MessageRemind.defaultProps = {
  disabled: false
};

function mapStateToProps (state) {
  const {tenant} = state.login;
  return {
    tenant
  };
}

export default connect(mapStateToProps)(MessageRemind);
